import axios from 'axios'
import { BASE_URL, TIMEOUT } from './config.js'
import { useAuthStore } from '@/stores/auth'

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 自动携带token
api.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    console.log(authStore.token)
    if (authStore.token) {
      config.headers.Authorization = authStore.token
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器 - 处理401自动跳转登录
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    if (error.response && error.response.status === 401) {
      const authStore = useAuthStore()
      authStore.clearToken()
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 登录API
export const login = async (username, password) => {
  const authStore = useAuthStore()
  try {
    const response = await api.post('/sysUser/login', {
      username,
      password
    })
    if (response.code === 0) {
      authStore.setToken(response.data.token)
      // 保存用户信息
      authStore.setUserInfo({
        username: username,
        ...response.data.userInfo
      })
      return {
        success: true,
        data: response.data,
        message: response.message
      }
    } else {
      return {
        success: false,
        message: response.message || '登录失败'
      }
    }
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '网络错误，请重试'
    }
  }
}

// 登出API
export const logout = () => {
  const authStore = useAuthStore()
  authStore.clearToken()
  // 可以在这里调用后端的登出接口
}

// 检查是否已登录
export const isLoggedIn = () => {
  const authStore = useAuthStore()
  return !!authStore.token
}

export default api 